import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  ColorPicker,
  Switch,
  Space,
  message,
  Popconfirm,
  Tag,
  Tooltip,
  InputNumber
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DragOutlined
} from '@ant-design/icons';
import { entityTypeApi } from '../../services/api';

const EntityTypeManager = ({ onTypeChange }) => {
  const [entityTypes, setEntityTypes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editing, setEditing] = useState(null);
  const [form] = Form.useForm();

  // 获取实体类型列表
  const fetchEntityTypes = async () => {
    setLoading(true);
    try {
      const response = await entityTypeApi.getEntityTypes({
        page: 1,
        pageSize: 100
      });
      
      if (response && response.success && response.data) {
        setEntityTypes(response.data.data || []);
      } else {
        message.error(response?.message || '获取实体类型失败');
      }
    } catch (error) {
      console.error('获取实体类型失败:', error);
      message.error('获取实体类型失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    fetchEntityTypes();
  }, []);

  // 添加实体类型
  const handleAdd = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({
      enabled: true,
      sortOrder: entityTypes.length + 1
    });
    setIsModalVisible(true);
  };

  // 编辑实体类型
  const handleEdit = (record) => {
    setEditing(record);
    form.setFieldsValue({
      ...record,
      color: record.color
    });
    setIsModalVisible(true);
  };

  // 保存实体类型
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 处理颜色值
      if (typeof values.color === 'object' && values.color.toHexString) {
        values.color = values.color.toHexString();
      }
      
      let response;
      if (editing) {
        response = await entityTypeApi.updateEntityType(editing.id, values);
      } else {
        response = await entityTypeApi.createEntityType(values);
      }
      
      if (response && response.success) {
        message.success(response.message || (editing ? '更新成功' : '添加成功'));
        setIsModalVisible(false);
        fetchEntityTypes();
        onTypeChange && onTypeChange(); // 通知父组件更新
      } else {
        message.error(response?.message || '操作失败');
      }
    } catch (error) {
      if (error.errorFields) {
        return;
      }
      console.error('保存失败:', error);
      message.error(error.message || '操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除实体类型
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const response = await entityTypeApi.deleteEntityType(id);
      
      if (response && response.success) {
        message.success(response.message || '删除成功');
        fetchEntityTypes();
        onTypeChange && onTypeChange(); // 通知父组件更新
      } else {
        message.error(response?.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error(error.message || '删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 切换启用状态
  const handleToggleEnabled = async (id, enabled) => {
    try {
      setLoading(true);
      const response = await entityTypeApi.toggleEnabled(id, enabled);
      
      if (response && response.success) {
        message.success(response.message || (enabled ? '启用成功' : '禁用成功'));
        fetchEntityTypes();
        onTypeChange && onTypeChange(); // 通知父组件更新
      } else {
        message.error(response?.message || '操作失败');
      }
    } catch (error) {
      console.error('切换状态失败:', error);
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 更新排序
  const handleUpdateSortOrder = async (id, sortOrder) => {
    try {
      const response = await entityTypeApi.updateSortOrder(id, sortOrder);
      
      if (response && response.success) {
        fetchEntityTypes();
      } else {
        message.error(response?.message || '更新排序失败');
      }
    } catch (error) {
      console.error('更新排序失败:', error);
      message.error('更新排序失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '排序',
      dataIndex: 'sortOrder',
      width: 80,
      render: (value) => (
        <div style={{ width: 60, textAlign: 'center' }}>
          {value}
        </div>
      )
    },
    {
      title: '类型代码',
      dataIndex: 'typeCode',
      width: 120,
      render: (text) => <code>{text}</code>
    },
    {
      title: '类型名称',
      dataIndex: 'typeName',
      render: (text, record) => (
        <Space>
          <div
            style={{
              width: 12,
              height: 12,
              borderRadius: '50%',
              backgroundColor: record.color,
              display: 'inline-block'
            }}
          />
          {text}
        </Space>
      )
    },
    {
      title: '颜色',
      dataIndex: 'color',
      width: 100,
      render: (color) => (
        <Tag color={color} style={{ minWidth: 60, textAlign: 'center' }}>
          {color}
        </Tag>
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      width: 80,
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handleToggleEnabled(record.id, checked)}
          size="small"
        />
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      render: (time) => time ? new Date(time).toLocaleString() : ''
    },
    {
      title: '操作',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="编辑">
            <EditOutlined
              onClick={() => handleEdit(record)}
              style={{ cursor: 'pointer', color: '#1890ff' }}
            />
          </Tooltip>
          <Popconfirm
            title="确认删除？"
            description="删除后将无法恢复，且可能影响使用该类型的实体"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <DeleteOutlined
                style={{ cursor: 'pointer', color: 'red' }}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          添加类型
        </Button>
      </div>

      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={entityTypes}
        pagination={false}
        size="small"
        scroll={{ y: 400 }}
      />

      {/* 添加/编辑 Modal */}
      <Modal
        title={editing ? '编辑实体类型' : '添加实体类型'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
        confirmLoading={loading}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            enabled: true,
            sortOrder: 1
          }}
        >
          <Form.Item
            name="typeCode"
            label="类型代码"
            rules={[
              { required: true, message: '请输入类型代码' },
              { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '类型代码只能包含字母、数字和下划线，且必须以字母开头' }
            ]}
          >
            <Input placeholder="请输入类型代码，如：concept" />
          </Form.Item>

          <Form.Item
            name="typeName"
            label="类型名称"
            rules={[{ required: true, message: '请输入类型名称' }]}
          >
            <Input placeholder="请输入类型名称，如：概念" />
          </Form.Item>

          <Form.Item
            name="color"
            label="类型颜色"
            rules={[{ required: true, message: '请选择类型颜色' }]}
          >
            <ColorPicker
              showText
              format="hex"
              presets={[
                {
                  label: '推荐颜色',
                  colors: [
                    '#722ed1', '#1890ff', '#52c41a', '#faad14',
                    '#f5222d', '#13c2c2', '#eb2f96', '#fa8c16',
                    '#a0d911', '#2f54eb', '#722ed1', '#fa541c'
                  ]
                }
              ]}
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="类型描述"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入类型描述"
            />
          </Form.Item>

          <Form.Item
            name="sortOrder"
            label="排序序号"
            rules={[{ required: true, message: '请输入排序序号' }]}
          >
            <InputNumber
              min={1}
              placeholder="数字越小排序越靠前"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="enabled"
            label="启用状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default EntityTypeManager;